<template>
  <div class="layout-container contract-template">
    <div class="app-container contract-template-header">
      <title-view title="新建模板" />
      <div class="option-buttons">
        <div class="save" @click="handelSave(true)">
          <el-icon>
            <Download />
          </el-icon>
          提交且下载合同模板
        </div>
        <div class="divider"></div>
        <div class="cancel" @click="handelSave(false)">提交</div>
        <div class="divider"></div>
        <div class="cancel" @click="handelCancel">取消</div>
      </div>
    </div>
    <div class="contract-template-body">
      <div class="app-container base-info" v-loading="isLoadingField">
        <template v-for="item in baseFields" :key="item.key">
          <div class="base-info-text" v-if="item.key !== 'other'">
            <div class="base-info-title">{{ item.name }}</div>
            <div class="list-item" v-for="subItem in item.content" :key="subItem.key">
              <span class="list-item-label">{{ subItem.name }}</span>
              <svg-icon iconClass="copy" @click="handelCopy(subItem.name)" />
            </div>
          </div>
          <div class="base-info-img" v-else>
            <div class="base-info-title">{{ item.name }}</div>
            <VueDraggableNext
              class="drag-from"
              :sort="false"
              :list="item.content"
              :group="{ name: 'imgList', pull: 'clone', put: false }"
              chosen-class="choose"
            >
              <div class="list-item" v-for="subItem in item.content" :key="subItem.key">{{ subItem.name }}</div>
            </VueDraggableNext>
          </div>
        </template>
      </div>
      <div class="template-design" id="template-design">
        <el-form :model="formData" :rules="formDataRules" ref="templateFormRef" v-loading="isLoadingDetail">
          <div class="app-container design-header">
            <div class="design-header-left">
              <el-form-item label="签约主体" prop="templateContractSignId">
                <el-select
                  popper-class="select-user-popper"
                  clearable
                  v-model="formData.templateContractSignId"
                  placeholder="请选择"
                  @change="handelChangeTemplateContractSign"
                >
                  <template #header>
                    <div class="content-item-search">
                      <el-input
                        placeholder="请输入关键词"
                        v-model="templateContractSignKeyword"
                        @change="searchTemplateContractSign"
                      />
                      <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="searchTemplateContractSign" />
                    </div>
                  </template>
                  <el-option
                    v-for="userItem in templateContractSigns"
                    :key="userItem.signId"
                    :label="userItem.enterpriseName"
                    :value="userItem.signId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="模板简介" style="margin-left: 23px" prop="introduction">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  placeholder="请输入商品名称90个字符以内"
                  :rows="1"
                  resize="none"
                  maxlength="90"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </div>
            <span class="code">合同编号（局）{{ `\${ ${contractCode.templateContentTitle} }` }}</span>
          </div>
          <!--       合同主体内容 start   -->
          <div class="app-container main-content">
            <el-form-item label="合同标题" prop="templateName">
              <el-input v-model="formData.templateName" />
            </el-form-item>
            <div class="main-content-title">主体内容</div>
            <EditorInput v-model="mainContent.templateContent" :is-disabled="false" editId="mainContent" />
          </div>
          <!--       合同主体内容 end   -->

          <!--      附加模块 start    -->
          <div class="additional-modules" v-for="(item, index) in formData.templateContentList">
            <div class="divider"></div>
            <div class="app-container">
              <div class="additional-modules-header">
                <el-form-item
                  :prop="'templateContentList.' + index + '.templateContentTitle'"
                  label="模块名称"
                  :rules="{ required: true, message: '请输入模块名称', trigger: 'change' }"
                >
                  <el-input
                    v-model="item.templateContentTitle"
                    type="textarea"
                    placeholder="请输入商品名称90个字符以内"
                    :rows="1"
                    resize="none"
                    maxlength="90"
                    show-word-limit
                  ></el-input>
                </el-form-item>
                <el-checkbox-group v-model="item.templateConfig">
                  <el-checkbox :label="1">强制阅读</el-checkbox>
                  <el-checkbox :label="2">确认签字</el-checkbox>
                  <el-checkbox :label="3">可以修改</el-checkbox>
                  <el-checkbox :label="4">横版显示</el-checkbox>
                </el-checkbox-group>
                <svg-icon iconClass="del" @click="handelDelTemplate(index)" />
              </div>
              <div class="placeholder-image-container">
                <VueDraggableNext class="drag-from" :list="item.topImgList" group="imgList" chosen-class="choose">
                  <div class="placeholder-image" v-for="(cp, index) in item.topImgList">
                    <div class="placeholder-image-item">
                      <div class="del-icon" @click="removeImg(item.topImgList, index)">
                        <el-icon>
                          <Close />
                        </el-icon>
                      </div>
                      <el-image class="placeholder-image" :src="cp.url" :preview-src-list="[cp.url]"></el-image>
                    </div>
                  </div>
                </VueDraggableNext>
              </div>
              <EditorInput v-model="item.templateContent" :editId="`placeholderContent${index}`" />
              <div class="placeholder-image-container">
                <VueDraggableNext class="drag-from" :list="item.bottomImgList" group="imgList" chosen-class="choose">
                  <div class="placeholder-image-item" v-for="cp in item.bottomImgList">
                    <div class="del-icon" @click="removeImg(item.bottomImgList, index)">
                      <el-icon>
                        <Close />
                      </el-icon>
                    </div>
                    <el-image :src="cp.url" :preview-src-list="[cp.url]"></el-image>
                  </div>
                </VueDraggableNext>
              </div>
            </div>
          </div>
          <!--      附加模块 end    -->
        </el-form>
      </div>
    </div>

    <!--  添加模块 start  -->
    <img class="add-template-img" :src="addTemplateIcon" @click="handelAddTemplate" />
    <!--  添加模块 end  -->
  </div>
</template>
<script setup>
import { ref, nextTick, getCurrentInstance } from "vue";
import { Close } from "@element-plus/icons-vue";
import { VueDraggableNext } from "vue-draggable-next";
import { cloneDeep, debounce } from "lodash";
import { useRouter, useRoute } from "vue-router";
import { useRouteQuery } from "@vueuse/router";
import EditorInput from "../../components/editorInput";
import paymentplanIcon from "@/assets/images/paymentplan-icon.png";
import addTemplateIcon from "@/assets/images/add-template.png";
import { scrollToBottom, handelCopy, downloadByData } from "@/utils/util.js";
import {
  contractTemplateConfig,
  createContractTemplate,
  updateContractTemplate,
  contractTemplateDetail,
  downContractTemplate,
  templateSet
} from "@/apis/contractTemplate/index.js";
import { signList } from "@/apis/contractingParty/index.js";
import { table, table1 } from "@/views/newTemplateList/moke.js";
import { setHtml } from "@/views/newTemplateList/setHtml.js";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
/**
 * 基础字段
 */
const isLoadingField = ref(false);
const baseFields = ref([]);
const templateId = useRouteQuery("templateId");
const isLoadingDetail = ref(false);

/**
 * 合同模板form
 */
const contractCode = ref({
  templateContentTitle: "合同编号",
  templateContentKey: ["contract_ode"],
  templateContent: "<span>合同编号（局）${ 合同编号 }</span>",
  templateContentSort: 0
});
const mainContent = ref({
  templateContentTitle: "主体内容",
  templateContentKey: [],
  templateContent: "",
  templateContentSort: 1
});
const templateData = {
  topImgList: [],
  bottomImgList: [],
  templateContentKey: "", //模板内容key
  templateContent: "", //模板内容
  templateContentTitle: "", //模板内容标题
  templateContentSort: "", // 内容排序
  templateConfig: [],
  isRead: false,
  isSign: false,
  isModifiable: false,
  isHorizontal: false
};
const formData = ref({
  templateContractSignId: "", // 签约主体id
  templateName: "",
  description: "",
  templateContentList: []
});
const formDataRules = {
  templateContractSignId: [{ required: true, message: "请选择签约主体", trigger: "blur,change" }],
  description: [
    { required: true, message: "请输入模板简介", trigger: "change" },
    { max: 90, message: "模板简介不能超过90个字符", trigger: "change" }
  ],
  templateName: [{ required: true, message: "请输入合同标题", trigger: "change" }],
  templateContentTitle: [{ required: true, message: "请输入模块名称", trigger: "change" }]
};
// 预算清单横竖版
const constructionBudgetList = ref([]);
/**
 * 搜索签约主体
 */
const templateContractSigns = ref([]);
const templateContractSignKeyword = ref("");
const isShowLost = ref(""); // 报价中显示耗损率;1是0否
const isShowMainProduct = ref(""); // 报价中显示主材;1是0否
// 预算清单表和竖版配置
const getTemplateSet = async () => {
  const { data } = await templateSet();
  constructionBudgetList.value = data.constructionBudgetList;
  isShowLost.value = data.isShowLost;
  isShowMainProduct.value = data.isShowMainProduct;
};
getTemplateSet();
const removeImg = (list, index) => {
  console.log(list, index);
  list.splice(index, 1);
};

const getTemplateDetail = async () => {
  if (!templateId.value) return;
  try {
    // isLoadingDetail.value = true;
    const { data } = await contractTemplateDetail(templateId.value);
    if (data.templateContentList?.length) {
      contractCode.value = cloneDeep(data.templateContentList[0]);
      mainContent.value = cloneDeep(data.templateContentList[1]);
      const templateContentList =
        data.templateContentList?.map((item, index) => {
          if (index > 1) {
            let templateConfig = [];
            item.isRead && templateConfig.push(1);
            item.isSign && templateConfig.push(2);
            item.isModifiable && templateConfig.push(3);
            item.isHorizontal && templateConfig.push(4);
            item.templateConfig = [...templateConfig];
            if (item.templateContent && isJSON(item.templateContent)) {
              const { topImg, bottomImg, templateContent } = JSON.parse(item.templateContent);
              item.bottomImgList = [...bottomImg];
              item.topImgList = [...topImg];
              item.templateContent = templateContent;
            }
            return item;
          }
        }) || [];
      data.templateContentList = [...templateContentList.slice(2)];
    }
    if (route.query.isCopy) {
      data.templateName = "";
      templateId.value = "";
      data.templateId = "";
    }
    formData.value = data;
    templateContractSigns.value.push({
      enterpriseName: data.templateContractSignName,
      signId: data.templateContractSignId
    });
    isLoadingDetail.value = false;
  } catch (err) {
    isLoadingDetail.value = false;
  }
};
const isJSON = str => {
  return typeof str === "string" && str.length > 0 && str[0] === "{" && str[str.length - 1] === "}";
};
const getContractTemplateConfig = async () => {
  try {
    isLoadingField.value = true;
    const { data } = await contractTemplateConfig();
    baseFields.value = data ?? [];
    baseFields.value?.forEach(item => {
      if (item.key === "other") {
        item.content.forEach(subItem => {
          subItem.url = paymentplanIcon;
        });
      }
    }) || [];
    isLoadingField.value = false;
  } catch (err) {
    isLoadingField.value = false;
  }
};

const getSignList = async () => {
  if (!templateContractSignKeyword.value) return;
  const { data } = await signList({ name: templateContractSignKeyword.value, status: true });
  templateContractSigns.value = data ?? [];
};
const searchTemplateContractSign = debounce(getSignList, 500);
const handelChangeTemplateContractSign = data => {
  // const obj = templateContractSigns.value.find(item => item.signId === data);
  // obj && (mainContent.value.templateContentTitle = obj.signName);
};

/**
 * 添加模块
 */
const handelAddTemplate = async () => {
  const cloneDeepData = cloneDeep(templateData);
  cloneDeepData.templateContentSort = formData.value.templateContentList.length + 1;
  formData.value.templateContentList.push(cloneDeepData);
  await nextTick();
  scrollToBottom("template-design");
};
/**
 * 删除模块
 */
const handelDelTemplate = index => {
  formData.value.templateContentList.splice(index, 1);
};

/**
 * 提交
 */
const getContentKeyByBaseFields = (matches, data) => {
  let keys = [];
  data.forEach(item => {
    item.content.forEach(subItem => {
      if (matches.includes(subItem.name)) {
        keys.push(subItem.contentKey);
      }
    });
  });
  return keys;
};
const getTemplateContentKey = templateContent => {
  const matches = templateContent?.match(/\$\{([^}]+)\}/g)?.map(match => match.slice(2, -1)) || [];
  const contentKeys = getContentKeyByBaseFields(matches, baseFields.value);
  return Array.from(new Set(contentKeys));
};
// 下载
const handelDown = async () => {
  let html = "";
  const mainData = cloneDeep(mainContent.value); // 主体内容
  const postData = cloneDeep(formData.value);
  html += mainData.templateContent.replace(/\${(.*?)}/g, "");
  postData.templateContentList.map((item, i) => {
    if (item.topImgList.length > 0) {
      item.topImgList.forEach(items => {
        if (items.name == "收款计划") {
          html += table;
        }
      });
    }
    if (item.templateContent) {
      html += item.templateContent = item.templateContent.replace(/\${(.*?)}/g, (match, key) => {
        if (key !== "工程预算清单") {
          return "";
        } else {
          let htmlOne = setHtml(constructionBudgetList.value, item.isHorizontal, isShowLost.value, isShowMainProduct.value);
          return (htmlOne += table1);
        }
      });
    }
    if (item.bottomImgList.length > 0) {
      item.bottomImgList.forEach(items => {
        if (items.name == "收款计划") {
          html += table;
        }
      });
    }
  });
  await downContractTemplate({
    name: formData.value.templateName,
    content: html
  }).then(res => {
    downloadByData(res, formData.value.templateName);
  });
};

// 提交
const handelSave = async type => {
  proxy.$refs.templateFormRef.validate(async val => {
    if (!val) return proxy.$modal.msgError("请完善信息");
    try {
      const mainData = cloneDeep(mainContent.value);
      const postData = cloneDeep(formData.value);
      // 主体文本字段数组
      mainData.templateContentKey = [...getTemplateContentKey(mainData.templateContent)];
      // 新增模块列表
      postData.templateContentList.forEach(item => {
        // TODO：暂时先实现功能
        item.isRead = item.templateConfig.indexOf(1) !== -1;
        item.isSign = item.templateConfig.indexOf(2) !== -1;
        item.isModifiable = item.templateConfig.indexOf(3) !== -1; //是否可以修改
        item.isHorizontal = item.templateConfig.indexOf(4) !== -1; //是否横版显示
        const topImg = item.topImgList?.length ? item.topImgList : [];
        const bottomImg = item.bottomImgList?.length ? item.bottomImgList : [];
        const obj = {
          topImg,
          bottomImg,
          templateContent: item.templateContent
        };
        item.templateContent = JSON.stringify(obj);
        item.templateContent.replace(/\${(.*?)}/g, (match, key) => {
          if (key === "工程预算清单") {
            item.templateFormHeader = JSON.stringify(constructionBudgetList.value);
          }
        });
        item.templateContentKey = [...getTemplateContentKey(item.templateContent)];
      });
      postData.templateContentList = [{ ...contractCode.value }, { ...mainData }, ...postData.templateContentList];
      const requestApi = templateId.value ? updateContractTemplate : createContractTemplate;
      await requestApi(postData, templateId.value);
      proxy.$modal.msgSuccess(`${templateId.value ? "模板更新成功！" : "模板新建成功！"}`);
      isLoadingDetail.value = false;
      if (type) {
        handelDown();
      }
      handelCancel();
    } catch (err) {
      isLoadingDetail.value = false;
    }
  });
};
const handelCancel = () => {
  router.replace({
    path: "/template-list"
  });
};

getContractTemplateConfig();
getTemplateDetail();
</script>

<style scoped lang="scss">
@import "newTemplateList";
</style>
<style lang="scss">
.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;

  .el-select-dropdown__header {
    padding: 10px 5px 0 5px !important;
  }

  .el-scrollbar__view > .el-select-dropdown__item {
    @include items-center;
    padding-left: 10px;
    padding-right: 10px;
    color: #3d3d3d;
    line-height: 22px;
  }

  .el-popper__arrow::before {
    display: none;
  }
}
</style>
